package cn.wolfcode.interceptor;


import cn.wolfcode.redis.service.ISecurityRedisService;
import cn.wolfcode.util.JSONResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class BlackListInterceptor implements HandlerInterceptor {

    @Autowired
    ISecurityRedisService securityRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 根据ip过滤黑名单用户
        String ip = request.getRemoteAddr().replace(":", ".");
        // 第一版本，使用set实现
        if (securityRedisService.inBlackList(ip)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(JSONResult.error(503, "访问过于频繁，此IP已被封禁24小时", "访问过于频繁，此IP已被封禁24小时")));
            return false;
        }
        return true;
    }
}
